﻿using System;
using System.Windows;

namespace Gmantis.Controls.Chart.Extended
{
    public class MovingAverage : FunctionSeries
    {
        // Fields
        public static readonly DependencyProperty PeriodProperty = DependencyProperty.Register("Period", typeof(int), typeof(MovingAverage), new PropertyMetadata(2, new PropertyChangedCallback(MovingAverage.OnPeriodChanged)));

        // Methods
        public MovingAverage()
        {
            base.Min = double.NaN;
            base.Max = double.NaN;
            base.Symbol = null;
            base.Connection = new Lines();
            base.ConnectionStrokeThickness = 2.0;
        }

        protected static void OnPeriodChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            int newValue = (int)args.NewValue;
            if (newValue < 1)
            {
                throw new ArgumentOutOfRangeException("Period must be greater than 1.");
            }
            ((MovingAverage)obj).UpdateData();
        }

        protected override double[,] ProcessValues(double[,] values)
        {
            if (values == null)
            {
                return values;
            }
            int length = values.GetLength(1);
            int period = this.Period;
            if (length <= period)
            {
                return null;
            }
            int num3 = (length - period) + 1;
            double[,] numArray = new double[2, num3];
            for (int i = 0; i < num3; i++)
            {
                int num5 = (i + period) - 1;
                double num6 = values[1, num5];
                double num7 = values[0, num5];
                for (int j = 1; j < period; j++)
                {
                    num7 += values[0, num5 - j];
                }
                num7 /= (double)period;
                numArray[1, i] = num6;
                numArray[0, i] = num7;
            }
            return numArray;
        }

        public override void UpdateData()
        {
            base.Invalidate();
        }

        // Properties
        public int Period
        {
            get
            {
                return (int)base.GetValue(PeriodProperty);
            }
            set
            {
                base.SetValue(PeriodProperty, value);
            }
        }
    }
}
